﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SF.Common;
using WeChat.Core.Common;
using WeChat.Core.ExtraCore;
using System.Data;
using System.Collections;
using System.Configuration;

namespace SF.Ucenter.admin.modeconfig
{
    public partial class malltemplet_list : Web.UI.ManagePage
    {
        SF.BLL.sf_modeconfig bll = new BLL.sf_modeconfig();
        protected Model.manager admin_info; //管理员信息
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                RptBind();

                IsNull();
            }
        }

        #region 数据绑定=================================
        /// <summary>
        /// 绑定模版,颜色
        /// </summary>
        /// <param name="wid"></param>
        private void RptBind()
        {
            try
            {
                rptPreview.DataSource = bll.GetList("onshelf=1 and isdelete=0");
                rptPreview.DataBind();
            }
            catch (Exception ex)
            {

            }
        }
        #endregion

        #region 数据绑定=================================
        private void IsNull()
        {
            try
            {
                //判断该公众号是否有模板
                admin_info = GetAdminInfo();
                SF.BLL.sf_appidmanage appmgr = new BLL.sf_appidmanage();
                SF.Model.sf_appidmanage mod = appmgr.GetModel(Session[DTKeys.SESSION_APP_INFO].ToString());
                string num = mod.templatesNum;
                //如果有
                if (!num.Equals(""))
                {
                    //得到与模板编号相同的id，给id传值
                    SF.BLL.sf_modeconfig bll = new BLL.sf_modeconfig();
                    object id = bll.GetID(num);
                    this.txtSelectTemplateId.Text = id.ToString();
                    hiddenGoodsType.Value = string.IsNullOrEmpty(mod.templatesNum) ? "" : new BLL.sf_modeconfig().GetModel("settingNum='" + mod.templatesNum + "'").goodstype_onshelf;

                }
                else
                {
                    //如果没有
                    this.lbl.Text = "请选择模板";
                    //Response.Write("<script>alert('请选择模板..')</script>");
                }
            }
            catch (Exception ex)
            {

            }
        }
        #endregion

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                //模板数据
                string s = hidden.Value;
                SF.BLL.sf_modeconfig bll = new BLL.sf_modeconfig();
                SF.Model.sf_modeconfig model = bll.GetModel(long.Parse(s.ToString()));
                //保存数据
                admin_info = GetAdminInfo();
                int a = admin_info.id;
                SF.BLL.sf_appidmanage appmgr = new BLL.sf_appidmanage();
                SF.Model.sf_appidmanage mod = appmgr.GetModel(Session[DTKeys.SESSION_APP_INFO].ToString());
                this.hidden1.Value = mod.templatesNum;
                //判断模板是否为空
                if (!mod.templatesNum.Equals(""))
                {
                    //判断修改的模板是否与原来的相同
                    if (!mod.templatesNum.Equals(model.settingNum))
                    {
                        //判断商城模版类型是否一致
                        //同类型模版间 当前公众号的 所有数据变更
                        //任何模版 都对抽成比例的 模版进行变更
                        string appwhere = "busnieseNum='" + mod.businessNum + "' and appNum='" + mod.appid + "' and templatesNum='" + mod.templatesNum + "'";
                        if (new BLL.sf_modeconfig().GetModel("settingNum='"+mod.templatesNum+"'").goodstype_onshelf.Equals(model.goodstype_onshelf))
                        {
                            BLL.sf_user_info userBll = new BLL.sf_user_info();
                            BLL.sf_goods_info goodsBll = new BLL.sf_goods_info();
                            BLL.sf_goods_amounts amountBll = new BLL.sf_goods_amounts();
                            BLL.sf_goods_cart cartBll = new BLL.sf_goods_cart();
                            BLL.sf_goods_color colorBll = new BLL.sf_goods_color();
                            BLL.sf_goods_img imgsBll = new BLL.sf_goods_img();
                            BLL.sf_goods_index_pics indexBll = new BLL.sf_goods_index_pics();
                            BLL.sf_goods_order orderBll = new BLL.sf_goods_order();
                            BLL.sf_goods_orderdetal orderdetalBll = new BLL.sf_goods_orderdetal();
                            BLL.sf_goods_size sizeBll = new BLL.sf_goods_size();
                            BLL.sf_goods_types typeBll = new BLL.sf_goods_types();
                            BLL.sf_user_address addressBll = new BLL.sf_user_address();
                            BLL.sf_user_bank bankBll = new BLL.sf_user_bank();
                            BLL.sf_user_withdraw_order withdrawBll = new BLL.sf_user_withdraw_order();
                            BLL.sf_auto_reply replyBll = new BLL.sf_auto_reply();

                            withdrawBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            bankBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            addressBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            cartBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            userBll.UpdateField("templatesNum='" + model.settingNum + "',sellModel="+model.marketing_type, appwhere);
                            sizeBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            colorBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            indexBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            typeBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            orderdetalBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            orderBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            amountBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            imgsBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            goodsBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            replyBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            mod.templatesNum = model.settingNum;
                            appmgr.Update(mod);
                            Session[DTKeys.SESSION_TEMPLATES_INFO] = model.settingNum;
                            JscriptShow("模版提示", "修改同类商城模版成功，数据已导入新模版中！若销售模式已更改，请按照规则重新生成自定义菜单！", "malltemplet_list.aspx");
                        }
                        else
                        {
                            //修改模版，用户信息 都要变更
                            BLL.sf_user_info userBll = new BLL.sf_user_info();
                            BLL.sf_auto_reply replyBll = new BLL.sf_auto_reply();
                            BLL.sf_user_address addressBll = new BLL.sf_user_address();
                            BLL.sf_user_bank bankBll = new BLL.sf_user_bank();
                            userBll.UpdateField("templatesNum='" + model.settingNum + "',sellModel=" + model.marketing_type, appwhere);
                            replyBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            addressBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                            bankBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);

                            mod.templatesNum = model.settingNum;
                            appmgr.Update(mod);
                            Session[DTKeys.SESSION_TEMPLATES_INFO] = model.settingNum;
                            JscriptShow("模版提示", "修改不同类商城模版成功，数据将冻结在原有模版中！若销售模式已更改，请按照规则重新生成自定义菜单！", "malltemplet_list.aspx");
                        }
                        //如果未存在提现比例 则创建 分销模式比例数据
                        BLL.sf_manager_scale scaleBll = new BLL.sf_manager_scale();
                        scaleBll.UpdateField("templatesNum='" + model.settingNum + "'", appwhere);
                        if (!scaleBll.Exists("busnieseNum='" + mod.businessNum + "' and appNum='" + mod.appid + "' and templatesNum='" + model.settingNum + "'"))
                        {
                            for (int i = 1; i < 4; i++)
                            {
                                Model.sf_manager_scale scale = new Model.sf_manager_scale();
                                scale.appNum = mod.appid;
                                scale.busnieseNum = admin_info.busnieseNum;
                                scale.templatesNum = mod.templatesNum;
                                scale.levelName = i == 1 ? "第一级" : i == 2 ? "第二级" : "第三级";
                                scale.levels = i;
                                scale.scale = 0;
                                scaleBll.Add(scale);
                            }
                        }
                        #region 变更模版后推送文本消息
                        IDictionary dict = ConfigurationManager.GetSection("weixinPay") as IDictionary;
                        string inf_uri = dict["inf_uri"].ToString();
                        string sendmsg_uri = dict["sendmsg_uri"].ToString();
                        api.wxpay.WebClient obj = new api.wxpay.WebClient();
                        string str = obj.GetHtml(inf_uri + "grant_type=client_credential&appid=" + mod.appid + "&secret=" + mod.appsecret);
                        SF.Ucenter.shallWeChat.wxaccesstoken p = api.wxpay.JsonHelper.JsonDeserialize<SF.Ucenter.shallWeChat.wxaccesstoken>(str);
                        WeChat.Core.Common.WeChatHttpHelper h = new WeChat.Core.Common.WeChatHttpHelper(sendmsg_uri);
                        DataTable dt = new BLL.sf_user_info().GetList("busnieseNum='" + mod.businessNum + "' and appNum='" + mod.appid + "' and templatesNum='" + model.settingNum + "'").Tables[0];
                        foreach (DataRow r in dt.Rows)
                        {
                            WeChatMessage data = new WeChatTextMessage() { Text = "商城模版已更新，请重新进入使用！", ToUser = r["openID"].ToString() };
                            var result = h.Post<WeChatBasicRs>(data.ToString(), new FormData { { "access_token", p.access_token } });
                        }
                        #endregion
                    }
                    else
                    {
                        JscriptMsg("未变更商城模版！", "");
                    }
                }
                else
                {
                    //保存模板编号
                    mod.templatesNum = model.settingNum;
                    appmgr.Update(mod);
                    Session[DTKeys.SESSION_TEMPLATES_INFO] = model.settingNum;
                    //创建 分销模式比例数据
                    BLL.sf_manager_scale scaleBll = new BLL.sf_manager_scale();
                    for (int i = 1; i < 4; i++)
                    {
                        Model.sf_manager_scale scale = new Model.sf_manager_scale();
                        scale.appNum = mod.appid;
                        scale.busnieseNum = admin_info.busnieseNum;
                        scale.templatesNum = mod.templatesNum;
                        scale.levelName = i == 1 ? "第一级" : i == 1 ? "第二级" : "第三级";
                        scale.levels = i;
                        scale.scale = 0;
                        scaleBll.Add(scale);
                    }
                    JscriptMsg("修改商城模版成功！", "malltemplet_list.aspx");
                }
            }
            catch (Exception ex)
            { }
        }

        protected string getType(string templateid) 
        {
            return new BLL.sf_modeconfig().GetModel(Convert.ToInt64(templateid)).goodstype_onshelf;
        }
    }
}